package com.atguigu.eduorder.controller;


import com.atguigu.commonutils.JwtUtils;
import com.atguigu.commonutils.R;
import com.atguigu.eduorder.entity.TOrder;
import com.atguigu.eduorder.service.TOrderService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 订单 前端控制器
 * </p>
 *
 * @author Cyrus
 * @since 2020-12-18
 */
@RestController
@RequestMapping("/eduorder/order")
public class TOrderController {

    @Autowired
    private TOrderService orderService;

    //生成订单
    @PostMapping("/createOrder/{courseId}")
    public R saveOrder(@PathVariable String courseId, HttpServletRequest request) {
        TOrder order = orderService.getOne(new QueryWrapper<TOrder>().lambda().eq(TOrder::getCourseId, courseId));
        if (order == null) {
            //创建订单返回订单号
            String orderNo = orderService.createOrder(courseId, JwtUtils.getMemberIdByJwtToken(request));
            return R.ok().data("orderNo", orderNo);

        } else {
            return R.ok().data("orderNo", order.getOrderNo());
        }


    }


    //查询订单信息
    @GetMapping("/getOrderInfo/{orderId}")
    public R getOrderInfo(@PathVariable String orderId) {
        TOrder orderInfo = orderService.getOne(new QueryWrapper<TOrder>().lambda().eq(TOrder::getOrderNo,orderId));
        return R.ok().data("orderInfo",orderInfo);
    }


    //查询当前课程是否已经购买
    @GetMapping("isBuyCourse/{courseId}/{memberId}")
    public boolean isBuyCourse(@PathVariable String courseId,@PathVariable String memberId) {
        int count = orderService.count(new QueryWrapper<TOrder>().lambda().eq(TOrder::getCourseId, courseId)
                .eq(TOrder::getMemberId, memberId)
                .eq(TOrder::getStatus, 1));
        if (count > 0) {
            return true;
        } else {
            return false;
        }
    }





}

